package com.zwq.poker.dto;

import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
public class TreeDTO {

    private String id;

    private String parentId;

    private List<TreeDTO> children;

    public static void main(String[] args) {
        List<TreeDTO> list = Arrays.asList(new TreeDTO("1", "0", null),
                new TreeDTO("2", "0", null),
                new TreeDTO("3", "0", null),
                new TreeDTO("4", "1", null),
                new TreeDTO("5", "4", null),
                new TreeDTO("6", "5", null)
        );

        Map<String, List<TreeDTO>> groupByParent = list.stream().collect(Collectors.groupingBy(TreeDTO::getParentId));

        List<TreeDTO> parents = groupByParent.get("0");
        //递归
//        findChildren(parents, groupByParent);

        //栈
        findChildrenByStack(parents, groupByParent);
        System.out.println(JSON.toJSONString(parents));

    }
    public static void findChildren( List<TreeDTO> parents, Map<String, List<TreeDTO>> groupByParent){
        if (CollectionUtils.isEmpty(parents)) {
            return;
        }
        for (TreeDTO parent : parents) {
            List<TreeDTO> children = groupByParent.get(parent.getId());
            findChildren(children, groupByParent);
            parent.setChildren(children);
        }
    }

    public static void findChildrenByStack(List<TreeDTO> parents, Map<String, List<TreeDTO>> groupByParent) {
        Stack<TreeDTO> patents = new Stack<>();
        patents.addAll(parents);

        while (!patents.isEmpty()) {
            TreeDTO pop = patents.pop();
            List<TreeDTO> children = groupByParent.get(pop.getId());
            if(!CollectionUtils.isEmpty(children)){
                patents.addAll(children);
                pop.setChildren(children);
            }

        }
    }


}

